package com.thenie.chat.interceptor;

import com.thenie.chat.pojo.User;
import com.thenie.chat.util.CookieUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

import static com.thenie.chat.util.WebSocketUtil.CURRENT_USER;
import static com.thenie.chat.util.WebSocketUtil.CURRENT_USER_ID;

/**
 * @Description
 * @Author thenie
 * @Data 2022/5/28 20:06
 */
@Component
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse,
                                   WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
        //获取httpServletRequest
        HttpServletRequest request = ((ServletServerHttpRequest)serverHttpRequest).getServletRequest();
        String userTicket = CookieUtil.getCookieValue(request, "userTicket");
        //判断是否存在cookie：userTicket
        if (StringUtils.isEmpty(userTicket) || !redisTemplate.hasKey("userTicket:"+userTicket)){
            return false;
        }
        User user = (User)redisTemplate.opsForValue().get("userTicket:" + userTicket);
        String userId = request.getParameter("userId");
        //判断cookie和用户id是否对应
        if (StringUtils.isEmpty(userTicket) || user.getId()!=Long.parseLong(userId)){
            return false;
        }
        //保存用户id
        attributes.put(CURRENT_USER_ID,userId);
        //保存用户user
        attributes.put(CURRENT_USER,user);
        return true;
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) {
        super.afterHandshake(request, response, wsHandler, ex);
    }
}
